/* global $ */

const SAMPLE = `【中国银行】今日外汇牌价:
积存金：306.26元/克
美元674.53，澳元485.78，
加元513.20，瑞郎676.98,
欧元768.74，英镑885.53,
日元6.0949，港币85.91，
韩元0.6241，卢布10.65,
新西兰470.23，泰铢22.39,
新台币22.73，新加坡501.06,
丹麦克朗103.07，
采集时间09:54
牌价实时变化，仅供参考`

function parseTime (text) {
  return text.replace(/[^]*采集时间\s*(\d{1,2}:\d{1,2})[^]*/m, '$1')
}

function parseItem (text) {
  const index = text.search(/\d+/)
  if (index === -1) {
    throw new Error('解析错误，请联系作者')
  } else {
    const key = text.substring(0, index).replace(/[:：]/, '')
    const value = text.substring(index, text.length)
    return [key, value]
  }
}

function parseItems (text) {
  const content = text.replace(/[^]*今日外汇牌价:([^]+?)采集时间[^]*/m, '$1')
  const items = content.split(/[,，\n]/)
    .map(x => $.trim(x))
    .filter(x => !!x)
    .map(x => parseItem(x))

  // 凑够双数
  if (items.length % 2 !== 0) {
    items.push(['', ''])
  }

  return items
}

function renderCover () {
  return new Promise((resolve, reject) => {
    const image = new window.Image()
    const index = Math.floor(Math.random() * (5 - 1 + 1)) + 1
    const url = `assets/images/${index}.jpg`
    image.onload = function () {
      $('#card .cover').css('background-image', `url(${url})`)
      resolve()
    }
    image.src = url
  })
}

function renderCard (text) {
  $('#canvas').hide()
  $('#card').show()

  const time = parseTime(text)
  const items = parseItems(text)
  let html = ''
  for (let i = 0; i < items.length; i++) {
    const [k, v] = items[i]
    if (i === 0) {
      html += '<tr>'
    } else if (i % 2 === 0 && i !== items.length) {
      html += '</tr><tr>'
    }

    html += `<td class="active">${k}</td><td class="text-right">${v}</td>`
  }
  html += '</tr>'
  $('#card .time').html(time)
  $('#card tbody').html(html)

  renderCover().then(() => {
    window.html2canvas($('#card .panel').get(0), { scale: 3 }).then(canvas => {
      $('#card').hide()
      $('#canvas').show()
      $('#canvas').html(`<img src="${canvas.toDataURL()}">`)
      // $('#canvas').empty().append(canvas)
    })
  })
}

function onFormSubmit (event) {
  event.preventDefault()
  const text = $.trim($('#text').val())
  if (text) {
    renderCard(text)
  } else {
    window.alert('没有输入内容')
  }

  return false
}

function fillSample () {
  $('#text').val(SAMPLE)
}

$(document).ready(function () {
  $('#form').submit(onFormSubmit)
  $('[data-toggle="tooltip"]').tooltip()
  $('#sample').click(fillSample)
})

if ('serviceWorker' in navigator) {
  window.addEventListener('load', function () {
    navigator.serviceWorker.register('sw.js')
  })
}
